package com.jzwl.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtil {

	private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

	public static Map<String, Object> requestByGetMethod(String url) {//get请求，去获取token
		//创建默认的httpClient实例
		CloseableHttpClient httpClient = getHttpClient();
		try {
			//用get方法发送http请求
			HttpGet get = new HttpGet(url);
			System.out.println("执行get请求:...." + get.getURI());
			CloseableHttpResponse httpResponse = null;
			//发送get请求
			httpResponse = httpClient.execute(get);
			Map<String, Object> map = new HashMap<String, Object>();
			try {
				//response实体
				HttpEntity entity = httpResponse.getEntity();
				if (null != entity) {
					System.out.println("响应状态码:" + httpResponse.getStatusLine());
					map.put("status", httpResponse.getStatusLine());
					System.out.println("-------------------------------------------------");
					String token = EntityUtils.toString(entity);
					System.out.println("响应内容:" + token);
					map.put("token", token);
					System.out.println("-------------------------------------------------");
				}
				return map;
			} finally {
				httpResponse.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				closeHttpClient(httpClient);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 模板消息
	 * @param url
	 * @param json 
	 * @param templateMessage  参数名称
	 * @return
	 */
	public static void requestByPostMethod(String url, String json, String templateMessage) {
		//创建默认的httpClient实例
		HttpClient httpClient = new HttpClient();
		try {

			PostMethod post = new PostMethod(url);
			post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			//设置参数
			NameValuePair[] param = { new NameValuePair("templateMessage", json) };
			post.setRequestBody(param);
			post.releaseConnection();
			log.info("执行post请求:...." + post.getURI());
			int codeStatus = 0;
			//发送get请求
			//	            httpClient.executeMethod(post);
			codeStatus = httpClient.executeMethod(post);
			log.info("+++++++++++++++++codeStatus+++++++++++++" + codeStatus);
			if (codeStatus == 200) {
				log.info("+++++++++++++++++is OK+++++++++++++++");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 普通文本消息
	 * @param url
	 * @param openId
	 * @param text
	 */
	public static void requestByPostMethodSendOpenId(String url, String openId, String text) {
		//创建默认的httpClient实例
		HttpClient httpClient = new HttpClient();
		try {

			PostMethod post = new PostMethod(url);
			post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			//设置参数
			NameValuePair[] param = { new NameValuePair("openId", openId), new NameValuePair("text", text) };
			post.setRequestBody(param);
			post.releaseConnection();
			log.info("执行post请求:...." + post.getURI());
			int codeStatus = 0;
			//发送get请求
			//	            httpClient.executeMethod(post);
			codeStatus = httpClient.executeMethod(post);
			log.info("+++++++++++++++++codeStatus+++++++++++++" + codeStatus);
			if (codeStatus == 200) {
				log.info("+++++++++++++++++is OK+++++++++++++++");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	//2
	public static void toTarget(String url) {//get请求，去bbs,zb目标地址
		//创建默认的httpClient实例
		CloseableHttpClient httpClient = getHttpClient();
		try {
			//用get方法发送http请求
			HttpGet get = new HttpGet(url);
			System.out.println("执行get请求:...." + get.getURI());
			CloseableHttpResponse httpResponse = null;
			//发送get请求
			httpResponse = httpClient.execute(get);
			try {
				//response实体
				HttpEntity entity = httpResponse.getEntity();
				if (null != entity) {
					System.out.println("响应状态码:" + httpResponse.getStatusLine());
					System.out.println("-------------------------------------------------");
					System.out.println("响应内容:" + EntityUtils.toString(entity));
					System.out.println("-------------------------------------------------");
				}
			} finally {
				httpResponse.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				closeHttpClient(httpClient);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static CloseableHttpClient getHttpClient() {
		return HttpClients.createDefault();
	}

	private static void closeHttpClient(CloseableHttpClient client) throws IOException {
		if (client != null) {
			client.close();
		}
	}

	public static String post(String url, Map<String, Object> paras) {

		// 创建默认的httpClient实例.  
		CloseableHttpClient httpclient = HttpClients.createDefault();

		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间

		// 创建httppost  
		HttpPost httppost = new HttpPost(url);

		httppost.setConfig(requestConfig);

		// 创建参数队列  
		List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();

		String result = "";

		if (paras != null || !paras.isEmpty()) {

			Iterator it = paras.entrySet().iterator();

			while (it.hasNext()) {

				Map.Entry entry = (Map.Entry) it.next();

				Object key = entry.getKey();

				Object value = entry.getValue();
				log.info("paras---" + key.toString() + "--" + value.toString());
				formparams.add(new BasicNameValuePair(key.toString(), value.toString()));
			}
		}

		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			log.info("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					log.info("--------------------------------------");
					//					logger.info("Response content: " +  EntityUtils.toString(entity, "UTF-8"));
					// EntityUtils.toString()只执行一次即关闭
					result = EntityUtils.toString(entity, "UTF-8");
					log.info("result:" + result);
					log.info("--------------------------------------");
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			log.info("ClientProtocolException");
			//			e.printStackTrace();
			return "ClientProtocolException";
		} catch (UnsupportedEncodingException e1) {
			log.info("UnsupportedEncodingException");
			//			e1.printStackTrace();
			return "UnsupportedEncodingException";
		} catch (IOException e) {
			log.info("IOException");
			//			e.printStackTrace();
			return "IOException";
		} finally {
			// 关闭连接,释放资源  
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String args[]) {

		Map mailInfo = new HashMap();

		mailInfo.put("host", "smtp.exmail.qq.com");

		mailInfo.put("totalPrice", "0.01");
		mailInfo.put("groupId", "1465883434999007");
		mailInfo.put("statusflag", "1");
		mailInfo.put("groupType", "1");
		mailInfo.put("schoolId", "1459324643109001");
		mailInfo.put("reciveName", "金 金 ");
		mailInfo.put("recivePhone", "15823698899 ");
		mailInfo.put("deliveryAddr", "北京市海淀区中关村中关村");
		mailInfo.put("remark", "哈哈");
		mailInfo.put("orderIdw", "0");
		mailInfo.put("groupnum", "1");
		mailInfo.put("out_trade_no", "1407091436_1_1465883434999007_0");
		mailInfo.put("openid", "oHxmUjm7EWgsuZTN0CN7aRU6ldIs");
		String mailUrl = "http://test.xiaoka360.com/wm-plat/weixin/toInsertOrChangeOrder.html";
		System.out.println(post(mailUrl, mailInfo));
	}

}
